import { EmployeesApi } from '@/api/Employees.api.js'
import { SysWelfarePercentEmployeeConfigApi } from '@/api/SysWelfarePercentEmployeeConfig.api.js'
import { SysWelfarePercentNoConfigApi } from '@/api/SysWelfarePercentNoConfig.api.js'
import { SysWelfarePercentAreaConfigApi } from '@/api/SysWelfarePercentAreaConfig.api.js'
import { FormShebaoFilter, FormShebaoFilterItem, FormShebaoTitle, FormShebao, FormShebaoItem } from './EBformData.js'
import { shebaoThead, shebaojiluThead } from './EBtableHead.js'
import _cloneDeep from 'clone-deep'
import { Common } from '@/utils/common.js'
import { EBbase } from './EBbase.js'

export default {
  props: {
    serviceFeeType: {
      type: Number,
      default: 0
    },
    isOnlyView: {
      type: Boolean,
      default: false
    },
    isInsuranceInfoSet: {
      type: Boolean,
      default: false
    }
  },

  data () {
    return {
      selectedEmployeeId: [], // 员工ID
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      insuranceId: '', // 保险ID
      formShebaoFilter: _cloneDeep(FormShebaoFilter),
      formShebaoFilterItem: _cloneDeep(FormShebaoFilterItem),
      formShebaoTitle: _cloneDeep(FormShebaoTitle),
      formShebao: _cloneDeep(FormShebao),
      formShebaoItem: _cloneDeep(FormShebaoItem),
      datePickerDefault: new Date(),
      rules: {},
      SecurityId: '', // 社保方案ID
      arrListDown: {
        securitys: [],
        securitysPlay1: []
      },
      shebaoThead: _cloneDeep(shebaoThead),
      shebaojiluThead: _cloneDeep(shebaojiluThead),
      tableData: [],
      recordTableData: [],
      selectedId: '',
      configInfo: {},
      isNext: false,
      dateOptions: {
        disabledDate (date) {
          const disabledDay = date.getDate()
          const month = date.getMonth()
          const nowMonth = (new Date()).getMonth()
          if (month === nowMonth) {

          } else {
            return disabledDay !== 1
          }
        }
      },
      isCanSave: true,
      allInsuranceNum: ''
    }
  },

  mounted () {
    this.employeeId = this.$route.query.employeeId // 员工ID
    this.companyId = this.$route.query.companyId // 公司ID
    this.companyName = this.$route.query.companyName // 公司名称

    this.getConfig()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    async handleSubmit (name) {
      var tempAmounts = []
      this.configInfo.details.map(item => {
        var aloneObg = { SecurityTypeCode: item.securityTypeCode }
        if (item.company) {
          aloneObg.CompanyBaseAmount = item.company.baseAmount
        }
        if (item.employee) {
          aloneObg.EmployeeBaseAmount = item.employee.baseAmount
        }
        tempAmounts.push(aloneObg)
      })
      console.log('tempAmounts: ', tempAmounts)

      var params = {
        id: this.insuranceId,
        securityType: 1, // 参保类型（1社会保险、2公积金）
        rangeGUID: this.formShebaoFilter.rangeGUID, // 社保编号
        employeeGUID: this.employeeId, // 员工ID
        securityGUID: this.formShebaoFilter.securityGUID, // 社保方案
        insuredTime: this.formShebaoFilter.insuredTime, // 参保时间
        description: this.formShebaoFilter.description, // 备注
        amounts: tempAmounts
      }
      let res = await SysWelfarePercentEmployeeConfigApi.saveShebaoOrGongjijin(params)
      console.log('提交表单res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.isNext = true
        this.$emit('saveSuccess', res.data.data)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 上一步
    handlepageUp () {
      Common.pageUp(this, 3) // '社保'的上一页，是'员工参保信息'，这个不会变
    },

    // 下一步
    handlepageDown () {
      if ([12, 23].indexOf(this.serviceFeeType) !== -1) { // 参保种类选择了'社保+社保' || '社保+社保+商保'
        Common.pageDown(this, 5) // 跳转到'社保'页面
      } else if (this.serviceFeeType === 13) { // 参保种类选择了'社保+商保'
        Common.pageDown(this, 6) // 跳转到'商保'页面
      } else {
        Common.pageDown(this)
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      let arr = value.map((item) => {
        return item.id
      })
      this.selectedId = arr.join(',')
      console.log('列表勾选', this.selectedId)
    },

    // 修改
    handleModify () {
      this.isNext = true
      this.$emit('handleModify', 4)
    },

    // 输入补缴月数计算参保时间
    toCountDate (form, month) {
      EBbase.toCountDate(this.formShebaoFilter, month)
    },

    // 输入参保时间计算补缴月数
    toCountMonth (form, date) {
      EBbase.toCountMonth(this.formShebaoFilter, date)
    },

    // 返回员工花名册列表
    goEmployeeBookList () {
      EBbase.goEmployeeBookList(this.$router, this.companyId, this.companyName)
    },

    // 根据ID获取员工参保基数配置信息
    async getConfig () {
      var params = {
        SecurityType: 1,
        CompanyGUID: this.companyId,
        EmployeeGUID: this.employeeId
      }
      let res = await SysWelfarePercentEmployeeConfigApi.getConfig(params)
      if (res.status === 200 && res.data.success && res.data.data.config) {
        var result = res.data.data
        this.configInfo = result.config // 保险信息
        this.insuranceId = result.config.id // 保险id
        // this.formShebaoFilter.securityGUID = result.config.securityGUID // 社保编号
        var tempSecuritys = result.securitys // 社保编号下拉框
        if (result.securitys) {
          result.securitys.map(item => {
            this.arrListDown.securitys.push({ label: item.text, value: item.value })
          })
        }

        if (result.config.rangeGUID) {
          this.getPlanList(result.config.rangeGUID, 1, this.arrListDown)
        }

        this.formShebaoFilter.rangeGUID = result.config.rangeGUID // 社保编号
        this.formShebaoFilter.securityGUID = result.config.securityGUID // 社保方案
        this.formShebaoFilter.description = result.config.description // 备注

        EBbase.parseConfigInfoIsOnlyView(this.configInfo, this.formShebaoFilter, this.tableData)
      }
    },

    // 获取社保编号
    async getAddModel (securityType, securityGUID, companyId) {
      var params = {
        SecurityType: securityType,
        SecurityGUID: securityGUID,
        CompanyGUID: companyId
      }
      let res = await SysWelfarePercentEmployeeConfigApi.getAddModel(params)
      console.log('获取社保编号res: ', res)
    },

    // 获取社保方案
    async getPlanList (securityGUID, securityType, arr) {
      this.arrListDown.securitysPlay1 = []
      this.formShebaoFilter.securityGUID = ''
      var tempArr = []
      var params = {
        CompanyGUID: this.companyId,
        SecurityType: securityType,
        SecurityNO: securityGUID
      }
      let res = await SysWelfarePercentNoConfigApi.getPlanList(params)
      console.log('获取社保方案res: ', res)
      if (res.status === 200 && res.data.success) {
        res.data.data.map(item => {
          tempArr.push({ label: item.text, value: item.value })
        })
      } else {
        tempArr = []
      }
      this.arrListDown.securitysPlay1 = tempArr
      this.allInsuranceNum = ''
    },

    // 拿到社保方案后获取的社保参数配置
    async getAddModel2 (selectId) {
      var params = {
        SecurityType: 1,
        CompanyGUID: this.companyId,
        SecurityGUID: selectId
      }
      let res = await SysWelfarePercentEmployeeConfigApi.getAddModel(params)
      console.log('拿到社保方案后获取的社保参数配置res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        this.configInfo = result.config // 保险信息
      }
    },

    // 默认基数改变时，重新计算缴纳金额
    async baseAmountOnBlur (baseAmount, precision, percent, section, rowIndex) {
      var params = {
        money: baseAmount, // 金额
        precision: precision, // 精度
        percent: percent // 比例
      }
      let res = await SysWelfarePercentAreaConfigApi.getTotalAmount(params)
      if (res.status === 200 && res.data.success) {
        console.log('计算单条缴纳金额res: ', res)
        if (res.status === 200 && res.data.success) {
          this.configInfo.details[rowIndex][section].totalAmount = res.data.data
        }
      }
    },

    // 所有险种输入框失去焦点时触发
    async allInsuranceOnBlue () {
      var tempArr = []
      this.configInfo.details.map(item => {
        if (item.company) {
          item.company.baseAmount = this.allInsuranceNum
          tempArr.push({
            money: item.company.baseAmount, // 金额
            precision: item.company.precision, // 精度
            percent: item.company.percent, // 比例
            securityTypeCode: item.securityTypeCode,
            isCompany: true
          })
        }
        if (item.employee) {
          item.employee.baseAmount = this.allInsuranceNum
          tempArr.push({
            money: item.employee.baseAmount, // 金额
            precision: item.employee.precision, // 精度
            percent: item.employee.percent, // 比例
            securityTypeCode: item.securityTypeCode,
            isCompany: false
          })
        }
      })
      console.log('tempArr: ', tempArr)

      let res = await SysWelfarePercentAreaConfigApi.getSecurityTotalAmountList({ Details: tempArr })
      console.log('所有险种输入框失去焦点时触发: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        result.map(item => {
          if (item.isCompany) {
            this.formShebao[item.securityTypeCode].Company.totalAmount = item.totalAmount
          } else {
            this.formShebao[item.securityTypeCode].Employee.totalAmount = item.totalAmount
          }
        })
        Object.keys(this.formShebao).forEach(key => {
          this.configInfo.details.map(item => {
            if (item.securityTypeCode === key) {
              if (item.company) {
                item.company.totalAmount = this.formShebao[key].Company.totalAmount
              }
              if (item.employee) {
                item.employee.totalAmount = this.formShebao[key].Employee.totalAmount
              }
              // item.employee.totalAmount = this.formShebao[key].Employee.totalAmount
            }
          })
        })
      }
    }
  }
}
